package com.woniu.springmybatis.tools;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;


import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * @author YuJunHong
 */
public class UpLoad {
    public static List upload2(HttpServletRequest request) throws Exception {
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        // 创建集合
        List lists=new ArrayList();
        //判断request是否有文件需要上传
        if (multipartResolver.isMultipart(request)) {
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            //取得request中的所有文件名
            Iterator<String> filenames = multiRequest.getFileNames();
            while (filenames.hasNext()) {
                //记录上传过程起始时时间，用来计算时间
                int pre = (int) System.currentTimeMillis();
                lists.add(pre);
                //取得上传文件
                MultipartFile file = multiRequest.getFile(filenames.next());
                if (file != null) {
                    //取得当前上传文件的名称
                    String myFileName = file.getOriginalFilename();
                    lists.add(myFileName);
                    //如果名称不为""，说明该文件存在，否则说明文件不存在。
                    if (myFileName.trim() != "") {
                        System.out.println(myFileName);
                        //重命名上传后的文件
                        String filename = "柳州" + file.getOriginalFilename();
                        //定义上传路径
                        String path = "D:\\eclipse\\workspace\\upload"+filename;
                        lists.add(path);
                        File localFile = new File(path);
                        file.transferTo(localFile);
                        return lists;
                    }
                }
            }
        }
        return lists;
    }

}
